using Unity.Burst;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Physics;
using Unity.Transforms;

partial struct MoverSystem : ISystem
{
    [BurstCompile]
    public void OnUpdate(ref SystemState state)
    {
        MoverJob moverJob = new MoverJob();
        moverJob.ScheduleParallel();
        //foreach((
        //    RefRW<LocalTransform> localTransform,
        //    RefRW<Mover> mover, 
        //    RefRO<Unit> unit,
        //    RefRW<PhysicsVelocity> physicsVelocity) 
        //    in SystemAPI.Query<
        //        RefRW<LocalTransform>,
        //        RefRW<Mover>, 
        //        RefRO<Unit>,
        //        RefRW<PhysicsVelocity>>())
        //{
        //    float3 moveDirection =
        //        math.normalize(mover.ValueRO.targetPos - localTransform.ValueRO.Position);
        //    float stopDistanceSq = 4f;

        //    if(math.distancesq(localTransform.ValueRO.Position, mover.ValueRO.targetPos) <= stopDistanceSq)
        //    {
        //        physicsVelocity.ValueRW.Linear = float3.zero;
        //        physicsVelocity.ValueRW.Angular = float3.zero;
        //    }
        //    else
        //    {
        //        physicsVelocity.ValueRW.Linear = moveDirection * unit.ValueRO.moveSpeed;
        //        physicsVelocity.ValueRW.Angular = float3.zero;
        //    }

            
        //}
    }
}

[BurstCompile]
public partial struct MoverJob : IJobEntity
{
    public void Execute(ref LocalTransform localTransform, ref Mover mover, in Unit unit, ref PhysicsVelocity physicsVelocity)
    {
        float3 moveDirection =
                math.normalize(mover.targetPos - localTransform.Position);
        float stopDistanceSq = 4f;

        if (math.distancesq(localTransform.Position, mover.targetPos) <= stopDistanceSq)
        {
            physicsVelocity.Linear = float3.zero;
            physicsVelocity.Angular = float3.zero;
        }
        else
        {
            physicsVelocity.Linear = moveDirection * unit.moveSpeed;
            physicsVelocity.Angular = float3.zero;
        }
        localTransform.Position.y = 0.1f;
        localTransform.Rotation = new float4(0, 0, 0, 1);
    }
}
